package com.xqboss.web.controller.sys;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xqboss.apps.domain.sys.Job;
import com.xqboss.apps.dto.sys.JobDto;
import com.xqboss.apps.vo.sys.JobTypeVo;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.core.domain.PageResult;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.exception.ServiceException;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import org.springframework.web.bind.annotation.RequestBody;
import com.xqboss.apps.service.sys.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 定时任务-按时间段配置
 * </p>
 *
 * @author 木鱼
 * @since 2024-03-11
 */
@RestController
@Slf4j
@Api(tags = "定时任务")
@RequestMapping("/web/jobs")
@RequiredArgsConstructor
public class JobController extends BaseController {

    private final JobService basicService;

    /**
     * 定时任务 列表查询
     */
    @PreAuthorize("@ss.hasPermi('web:job:list')")
    @GetMapping("/list")
    @ApiOperation("定时任务-列表查询")
    public R<List<JobTypeVo>> loadList() {
        //查询列表前，先把当前之间之前任务的置为过期状态
        basicService.setAsExpired(DateUtil.date());
        List<JobTypeVo> jobs = basicService.selectBasicList();
        return R.ok(jobs,"定时任务列表查询成功~");
    }

    /**
     * 定时任务-按时间段配置 列表查询
     */
    @PreAuthorize("@ss.hasPermi('web:job:config:list')")
    @GetMapping("/list-config")
    @ApiOperation("定时任务-按时间段配置 列表查询")
    public PageResult<Job> loadConfigList(@Validated JobDto<Job> dto) {
        IPage<Job> iPage = basicService.selectBasicConfigList(dto);
        return PageResult.ok(iPage);
    }

    /**
     * 定时任务-按时间段配置 停止/启用
     */
    @PreAuthorize("@ss.hasPermi('web:job:config:state')")
    @GetMapping("/state/{type}/{configId}")
    @Log(title = "定时任务(停止/启用)", businessType = BusinessType.UPDATE)
    @ApiOperation("定时任务-按时间段配置 停止/启用 （1-停止 2-开启）")
    public R<String> updateJobConfigState(@PathVariable
                                          @ApiParam(name = "type",value = "停止/开启状态值，（1-停止 2-开启）")
                                          @NotNull(message = "（1-停止 2-开启）")
                                          @Min(value = 1,message = "1-停止")
                                          @Max(value = 2,message = "2-开启")
                                              Integer type,
                                          @PathVariable
                                          @ApiParam(name = "configId",value = "定时任务配置id")
                                          @NotNull(message = "配置id不能为空~")
                                          Long configId) {
        String msg = type==1?"停止":"开启";
        try{
            basicService.updateJobConfigState(type,configId);
            return R.ok(msg + "成功~");
        }catch (Exception e){
            log.error("[updateJobConfigState]{}失败",msg,e);
            return R.ok(e.getMessage());
        }
    }

    /**
     * 定时任务-按时间段配置 新增
     */
    @PreAuthorize("@ss.hasPermi('web:job:config:info')")
    @PostMapping("/info/{id}")
    @ApiOperation("定时任务-按时间段配置 信息")
    public R<Job> info(@PathVariable  @ApiParam(name = "id",value = "任务id",required = true) @NotNull(message = "任务id不能为空~") String id) {
        Job job = basicService.getById(id);
        Assert.notNull(job,()->new ServiceException("未查询到队友定时任务信息~"));
        return R.ok(job,"定时任务成功信息~");
    }


    /**
     * 定时任务-按时间段配置 新增
     */
    @PreAuthorize("@ss.hasPermi('web:job:config:addOrEdit')")
    @PostMapping("/addOrEdit")
    @Log(title = "定时任务(新增或修改)", businessType = BusinessType.INSERT_OR_UPDATE)
    @ApiOperation("定时任务-按时间段配置 新增或修改（携带id）")
    public R<String> addOrEdit(@Validated @RequestBody Job record) {
        basicService.addOrEdit(record);
        return R.ok_msg(record.getId()==null?"添加":"编辑"+"任务成功~");
    }

    /**
     * 定时任务-按时间段配置 删除
     */
    @PreAuthorize("@ss.hasPermi('web:job:config:delete')")
    @GetMapping("/delete/{id}")
    @Log(title = "定时任务(移除)", businessType = BusinessType.UPDATE)
    @ApiOperation("定时任务-按时间段配置 删除")
    public R<String> delete(@PathVariable Long id) {
        basicService.removeBasic(id);
        return R.ok_msg("移除任务成功~");
    }
}
